package com.project.servlet;

import com.project.bean.EmployeeBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //将客户端提交的表单数据封装成实体对象
        EmployeeBean em = new EmployeeBean();
        this.fullBean(req,em);

        resp.getWriter().print(em);
    }

    /**
     * 将客户端提交的表单数据，封装成实体对象
     * @param req 请求对象
     * @param beanObj 实体对象
     */
    private void fullBean(HttpServletRequest req, Object beanObj) {
        Class beanClass = beanObj.getClass();
        //得到客户端提交服务器表单名
        Enumeration<String> em =  req.getParameterNames();
        try {
            while (em.hasMoreElements()) {
                //得到表单名
                String str = em.nextElement();
                //根据表单名，得到表单值
                String value = req.getParameter(str);
                //根据表单名，得到实体类的属性对象（表单名和属性名要一致）
                Field f = beanClass.getDeclaredField(str);
                f.setAccessible(true);

                if(f.getType() == String.class){
                    f.set(beanObj,value);
                }
                else if(f.getType() == int.class || f.getType() == Integer.class){
                    f.set(beanObj,Integer.parseInt(value));
                }
                else if(f.getType() == double.class || f.getType() == Double.class){
                    f.set(beanObj,Double.parseDouble(value));
                }
                else if(f.getType() == LocalDate.class){
                    f.set(beanObj,LocalDate.parse(value));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
